package com.piepesken.mediscale.ui.drugs

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.piepesken.mediscale.viewmodels.DrugViewModel
import com.piepesken.mediscale.viewmodels.SearchViewModel
import com.piepesken.mediscale.viewmodels.SearchWidgetState
import com.piepesken.mediscale.models.Drug
import com.piepesken.mediscale.ui.components.drugs.DrugItemRow
import com.piepesken.mediscale.ui.components.drugs.DrugSearchBar
import com.piepesken.mediscale.ui.components.drugs.DrugSearchBarButton


@Composable
fun DrugsScreen(
    navController: NavController
) {
    val viewModel: DrugViewModel = hiltViewModel()
    val searchViewModel: SearchViewModel = hiltViewModel()
    val drugs: List<Drug> by viewModel.drugs.collectAsState(initial = emptyList())
    var searchItems: MutableState<List<Drug>> = remember { mutableStateOf(emptyList()) }


    Column(
        modifier = Modifier
            .padding(16.dp)
            .fillMaxSize()
    ) {
        // Search bar
        when (searchViewModel.searchWidgetState.value) {
            SearchWidgetState.CLOSED -> {
                DrugSearchBarButton {
                    searchViewModel.updateSearchWidgetState(
                        SearchWidgetState.OPENED
                    )
                }
            } else -> {
                DrugSearchBar(
                    text = searchViewModel.searchTextState.value,
                    onTextChange = {
                        searchViewModel.updateSearchTextState(it)
                    },
                    onCloseClicked = {
                        searchViewModel.updateSearchWidgetState(
                            SearchWidgetState.CLOSED
                        )
                    },
                    onSearchClicked = {}
                )
            }
        }

        // Content
        LazyColumn {
            items(
                count = drugs.size,
                key = {
                    drugs[it].id
                }
            ) {
                    index -> if (drugs[index].name.contains(searchViewModel.searchTextState.value)) {
                        DrugItemRow(
                            title = drugs[index].name,
                            effect = drugs[index].effect!!,
                            onItemClick = {
                                navController.navigate("drug/${drugs[index].id}")
                            }
                        )
                    }
            }
        }
    }
}

